<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            @change="changePlant(searchParam.plantId)"
            v-model="searchParam.plantId"
            clearable
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in plants"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="呼叫类型">
          <el-select
            v-model="searchParam.callTypeId"
            @change="callChange"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="item in callTypes"
              :key="item.id"
              :label="item.callTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班组">
          <el-select
            v-model="searchParam.crewId"
            placeholder="请输入班组"
            clearable
            filterable
            @change="changeCrew"
          >
            <el-option
              v-for="item in crewList"
              :key="item.id"
              :label="`${item.crewCode}-${item.crewName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column
          label="安东呼叫编号"
          prop="callCode"
          width="190"
          show-overflow-tooltip
        />
        <el-table-column
          label="呼叫类型"
          prop="callTypeName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="安东操作"
          prop="operateSetting"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>{{
              useDictionary("AndonCallSetting", scope.row.operateSetting)
            }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="工厂编号"-->
        <!--          prop="plantCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="呼叫类型编码"-->
        <!--          prop="callTypeCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="班组编号"-->
        <!--          prop="crewCode"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="呼叫设定编号"-->
        <!--          prop="callSettingCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="工作中心"
          prop="workshopName"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.workCenterCode + "-" + scope.row.workCenterName }}
          </template>
        </el-table-column>
        <el-table-column
          label="工序"
          prop="processName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="设备"
          prop="equipmentName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="是否停机"
          prop="isStop"
          min-width="80"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isStop === 1">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="停机类型编码"-->
        <!--          prop="stopCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="停机原因编号"-->
        <!--          prop="stopReasonCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="呼叫时间"
          prop="callTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="响应时间"
          prop="answerTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="到场时间"
          prop="arriveTime"
          min-width="160"
          show-overflow-atooltip
          align="center"
        />
        <el-table-column
          label="解决时间"
          prop="issueTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="呼叫状态"
          prop="callState"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ useDictionary("CallState", scope.row.callState) }}
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="处理时长单位秒"-->
        <!--          prop="totalTime"-->
        <!--          min-width="150"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="处理人名"-->
        <!--          prop="processorName"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="是否触发报检"
          prop="autoInspection"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.autoInspection === 1"
              >是
            </el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <!--        <el-table-column-->
        <!--          label="报检类型编码"-->
        <!--          prop="inspectionTypeCode"-->
        <!--          min-width="120"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="备注"-->
        <!--          prop="remarks"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="创建时间"-->
        <!--          prop="createTime"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <!--        <el-table-column-->
        <!--          label="更新时间"-->
        <!--          prop="lastUpdateTime"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <!--        <el-table-column-->
        <!--          label="更新人名"-->
        <!--          prop="lastUpdatedUserName"-->
        <!--          min-width="100"-->
        <!--          show-overflow-tooltip-->
        <!--        />-->
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search />
              详情
            </el-button>
            <el-button
              v-if="scope.row.operateSetting != 2 && scope.row.callState === 1"
              type="primary"
              size="small"
              link
              @click="confirm(scope.row)"
            >
              <i-ep-edit />
              确认
            </el-button>
            <el-button
              v-if="scope.row.callState === 1"
              type="primary"
              size="small"
              link
              @click="cancel(scope.row)"
            >
              <i-ep-RefreshLeft />
              取消呼叫
            </el-button>
            <el-button
              v-if="scope.row.operateSetting == 2 && scope.row.callState < 9"
              type="primary"
              size="small"
              link
              @click="fugong(scope.row)"
            >
              <i-ep-Close />
              复工
            </el-button>
            <el-button
              v-if="scope.row.callState === 3"
              type="primary"
              size="small"
              link
              @click="close(scope.row)"
            >
              <i-ep-Close />
              关闭
            </el-button>
            <el-button
              v-if="
                scope.row.callState === 9 ||
                scope.row.callState === 10 ||
                scope.row.callState === 11
              "
              type="primary"
              size="small"
              link
              @click="repairInfo(scope.row)"
            >
              <i-ep-edit />
              维修单填写
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <andcall-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <andcall-repair
      :visible="repairDialog.visible"
      :title="repairDialog.title"
      :data="repairDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="repairDialog.readvisible"
      @change-visible="changeVisibleRepair"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import AndcallRepair from "@/views/andon/andcall/components/andcall-repair.vue";

defineOptions({
  name: "ANDONANDCALL",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/andon/andcall/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  organizationId: "",
  plantId: "",
  callTypeId: "",
  crewId: "",
  callSettingId: "",
  workCenterId: "",
};

const deleteParam = {
  api: "/andon/andcall/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

let plants = ref([]);
let callTypes = ref([]);
const crewList = ref([]);
const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const repairDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
  searchParam.value.plantId = plants.value[0].id;
  changePlant(searchParam.plantId);
}

function changePlant(id) {
  getCallTypes(id);
  getCrews(id);
}

async function getCallTypes(id) {
  const data = await request({
    url: "/andon/andcalltype/querycalltypes",
    method: "post",
    data: { plantId: id },
  });
  callTypes.value = data.data;
}

async function getCrews(id) {
  await request({
    url: "mes/mescrew/getCrew",
    method: "post",
    data: {
      plantId: id,
      enabled: 1,
    },
  }).then((res) => {
    crewList.value = res.data;
  });
}

// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `/andon/andcall/get/${id}`,
    method: "get",
  });
  addDialog.data = data;
  console.log("data", data);
}

/** 打开安东呼叫记录表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "安东呼叫升级记录";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
  addDialog.visible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function changeVisibleRepair(value: boolean) {
  repairDialog.visible = value;
  if (!value) {
    repairDialog.data = {};
  }
}

const close = (row) => {
  ElMessageBox.confirm("是否关闭已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/andon/andcall/updateCallState`,
      method: "post",
      data: { id: row.id, callState: 11 },
    })
      .then(() => {
        ElMessage.success("关闭成功");
        getTableList();
      })
      .catch(() => ElMessage.info("已取消关闭"));
  });
};

async function repairInfo(row) {
  repairDialog.title = "安东呼叫升级记录";
  const { data } = await request({
    url: `/andon/andcall/get/${row.id}`,
    method: "get",
  });
  repairDialog.data = data;
  repairDialog.readvisible = true;
  repairDialog.visible = true;
}

const cancel = (row) => {
  ElMessageBox.confirm("是否取消已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/andon/andcall/updateCallState`,
      method: "post",
      data: { id: row.id, callState: 2 },
    })
      .then(() => {
        ElMessage.success("取消成功");
        getTableList();
      })
      .catch(() => ElMessage.info("已取消"));
  });
};

const fugong = (row) => {
  ElMessageBox.confirm("是否复工已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/andon/andcall/updateCallState`,
      method: "post",
      data: { id: row.id, callState: 9 },
    })
      .then(() => {
        ElMessage.success("取消成功");
        getTableList();
      })
      .catch(() => ElMessage.info("已取消"));
  });
};
const confirm = (row) => {
  ElMessageBox.confirm("是否确认已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/andon/andcall/updateCallState`,
      method: "post",
      data: { id: row.id, callState: 3 },
    })
      .then(() => {
        ElMessage.success("确认成功");
        getTableList();
      })
      .catch(() => ElMessage.info("已取消确认"));
  });
};
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
